/* ********************************************************** */
/*!	
	\brief Writes and reads an 8-bit byte via SPI.

	\note Selects hardware or software SPI based on constant
	 defintion SPI0_SOFT.

	\author Joe Pardue 
	\date October 29, 2010
	\version 1.00
*/
/* ********************************************************** */
uint8_t spi0_master_rw8(uint8_t to_slave)
{
	#if defined (SPI0_SOFT)
	return spi0_soft_master_rw8(to_slave);
	#else // HARD
	return spi0_hard_master_rw8(to_slave);
	#endif
}


/* ********************************************************** */
/* ********************************************************** */
/*!	
	\brief Writes and reads an 8-bit byte via software SPI
	for spi0.

	\note Selects hardware or software SPI based on constant
	 defintion SPI0_SOFT

	\return 8-bit byte from the slave device.

	\param to_slave - 8-bit byte to send to the slave device.

	\author Joe Pardue 
	\date October 29, 2010
	\version 1.00
*/
/* ********************************************************** */
uint8_t spi0_soft_master_rw8(uint8_t to_slave)
{
	uint8_t from_slave = 0;

	spi_soft_set_ss();

	for(int i=0; i<=7; i++)
	{
		// Send a bit
		if(is_bit_set(to_slave,i))
			spi_soft_set_mosi_bit();
		else
			spi_soft_clear_mosi_bit();

		// Receive a bit
		// temp bits start 0 so change only if 1
		if (miso_port_pins & (1<<miso_port_pin))
			from_slave |= (1 << i);

   		// Toggle the clock
    	spi_soft_toggle_sclk();
	}

	spi_soft_clear_ss();

	return from_slave;

}

/* ********************************************************** */
/* ********************************************************** */
/*!	
	\brief Writes and reads an 8-bit byte via hardware SPI
	for spi0.

	\note Blocks waiting for send to complete

	\return 8-bit byte from the slave device.

	\param to_slave - 8-bit byte to send to the slave device.

	\author Joe Pardue 
	\date October 29, 2010
	\version 1.00
*/
/* ********************************************************** */
uint8_t spi0_hard_master_rw8(uint8_t to_slave)
{
	uint8_t from_slave;

	// select slave
	spi_hard_set_ss();

	// Put byte in SPI data register
	SPDR = to_slave;	

	// Poll SPIF-flag until transfer complete				
	while(!(SPSR & (1<<SPIF)));					

	// Get the SPI data reg.
	from_slave = SPDR;	

	// deselect slave
	spi_hard_clear_ss();
							
	//return it
	return from_slave;
							
}

/* ********************************************************** */
